package cn.utry.sipGateWay.netty;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.utry.sipGateWay.config.SiriConfig;
import cn.utry.sipGateWay.sip.MsgKey;
import cn.utry.sipGateWay.sip.SessionContainer;
import cn.utry.sipGateWay.sip.SipMessageUtil;
import cn.utry.sipGateWay.sip.SipMsgKey;
import cn.utry.sipGateWay.sip.SipSession;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class SipMsgHandler extends SimpleChannelInboundHandler<DatagramPacket> {
	private static final Logger log = LoggerFactory.getLogger(SipMsgHandler.class);
    //接受服务端发送的内容
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
    	String response=packet.content().toString(StandardCharsets.UTF_8);
    	log.info("收到了服务端的响应 !");
    	log.info("\n {}",response);
    	String ackMsg="";
    	Map<String,Object> map=SipMessageUtil.reciveMsg(response);
    	if(map.get(SipMessageUtil.msgType).equals(MsgKey.RESPONSE)) {
    		if(map.get(SipMessageUtil.responseCode).equals("200")) {
				String callId=map.get(SipMsgKey.Call_ID).toString();
				SipSession session=SessionContainer.getSession(callId);
    			map.put(SipMsgKey.URL, map.get(SipMsgKey.Contact));
    			map.put(SipMsgKey.User_Agent, session.getInviteMap().get(SipMsgKey.User_Agent));
    			map.put(SipMsgKey.Contact, session.getInviteMap().get(SipMsgKey.Contact));	
    			map.put(SipMsgKey.Via, session.getInviteMap().get(SipMsgKey.Via));    		
				ackMsg=SipMessageUtil.getAckMsg(map);
    		}
    	}
    	if(!ackMsg.isEmpty()) {
            // 向服务端发送消息
            ByteBuf byteBuf = Unpooled.copiedBuffer(ackMsg.getBytes(StandardCharsets.UTF_8));
            ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
            log.info("向服务{}:{}发送ack。。。。。。",SiriConfig.SERVER_IP,SiriConfig.SERVER_PORT);
			log.info("\n {}",ackMsg);
    	}

    }
 
}